﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Coolite.Ext.Web;
using System.Collections.Generic;

using Sagacity.NC.Web.FormForm;
using Sagacity.NC.Business.SysMange;

namespace Sagacity.NC.Web.Form
{
    public partial class WebTreeControl : System.Web.UI.UserControl
    {
        #region 资源配置属性
        /// <summary>
        /// 资源数据过滤条件
        /// </summary>
        private List<Sagacity.Entity.Query.FilterInfo> filters = new List<Sagacity.Entity.Query.FilterInfo>();
        public List<Sagacity.Entity.Query.FilterInfo> Filters { get { return filters; } set { filters = value; } }

        /// <summary>
        /// 登陆人员信息
        /// </summary>
        public Sagacity.NC.Business.SysMange.FormUser CurrentUser { get; set; }

        public Sagacity.Entity.Build.RoleInfo Role { get; set; }

        /// <summary>
        /// 当前Form对应的资源
        /// </summary>
        public int resourceId { get; set; }

        /// <summary>
        /// 当前Form表单操作表
        /// </summary>
        public string TableName { get; set; }

        /// <summary>
        /// 当前Form表单操作表的主键列名称
        /// </summary>
        public string TableKey { get; set; }

        /// <summary>
        /// 需要添加的字段以及对应的值
        /// </summary>
        private Hashtable addFields = new Hashtable();
        public Hashtable AddFieldS { get { return addFields; } set { addFields = value; } }

        System.Data.DataTable dt = new DataTable();
        System.Data.DataTable dtitem = new DataTable();
        
        /// <summary>
        /// 在数据集合中树形需要保留的字段
        /// </summary>
        public string[] arrayString = new string[] { };
        
        /// <summary>
        /// 获得点击树节点跳转的路径
        /// </summary>
        public string url { get; set; }

        /// <summary>
        /// 根节点显示的名称
        /// </summary>
        public string title { get; set; }

        /// <summary>
        /// 是否显示工具栏，搜索
        /// </summary>
        public bool toolstarte { get; set; }

        /// <summary>
        /// 设置模型参数
        /// </summary>
        private List<Sagacity.Entity.Query.ParameterInfo> modelparams = new List<Sagacity.Entity.Query.ParameterInfo>();
        public List<Sagacity.Entity.Query.ParameterInfo> ModelParams { get { return modelparams; } set { modelparams = value; } }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.hidUrl.Value = url;
                GetShowDataTable(true);
                //控制树形一级的名称
                if (!string.IsNullOrEmpty(title))
                {
                    TreePanel.RootVisible = true;
                    TreePanel.Root[0].Text = title;
                    //第一个树节点点击事件
                    //((Coolite.Ext.Web.AsyncTreeNode)TreePanel.Root[0]).Listeners.Click.Handler = "javascript:showForm(node)";
                }
                else
                    TreePanel.RootVisible = false;

                txtFieldSearch.Visible = toolstarte;
                btnSearch.Visible = toolstarte;
                ToolbarButton1.Visible = toolstarte;
                ToolbarButton2.Visible = toolstarte;
            }
        }

        /// <summary>
        /// 获得数据
        /// </summary>
        /// <param name="refresh">是否需要重新刷新</param>
        public void GetShowDataTable(bool refresh)
        {
            string cachekey = ("TreeData_" + TableName + "_" + CurrentUser.LoginRole.Id).ToUpper();

            CacheManage.RefreshCacheDependencyObject(DataSourceType.ResourceData, resourceId);
            object obj = CacheManage.GetCacheObject(cachekey);

            if (obj != null && !refresh)
            {
                dtitem = (DataTable)obj;
            }
            else
            {
                dtitem =  Sagacity.NC.Business.SysMange.Common.GetRoleRightData(CurrentUser.LoginRole, resourceId, filters, ModelParams);
                CacheManage.AddCacheObject(cachekey, dtitem, DataSourceType.ResourceData, resourceId);
            }
        }

        /// <summary>
        /// 根据节点编号显示出下面的子节点
        /// </summary>
        /// <param name="nodeID">节点编号</param>
        /// <returns></returns>
        [AjaxMethod]
        public string InitTree(string nodeID)
        {
            //string cachekey = ("TreeData_" + TableName + "_" + CurrentUser.LoginRole.Id).ToUpper();
            string txtseach = txtFieldSearch.Text;
            string keyId = AddFieldS["keyId"].ToString();
            string keyname = AddFieldS["keyName"].ToString();
            string keyparent = AddFieldS["keyParent"].ToString();

            Coolite.Ext.Web.TreeNodeCollection nodes = new Coolite.Ext.Web.TreeNodeCollection();
            try
            {
                GetShowDataTable(false);

                //对数据集进行排序处理
                Sagacity.Entity.Build.ResourceInfo resourceInfo = new Sagacity.Entity.Build.ResourceInfo();
                //根据资源号查询数据字段
                resourceInfo = (new Sagacity.Build.Application.Resource()).GetResrouse(resourceId);
                //排序处理
                string sort = Sagacity.NC.Business.SysMange.Common.GetSortData(resourceId, resourceInfo.Fields);


                System.Data.DataRow[] dv = new DataRow[] { };
                dv = dtitem.Select(keyparent + " =" + nodeID, sort);
                if (dv.Length < 1 && nodeID == "0")
                {
                    getDataRow(dtitem, ref  dv, sort);
                }

                foreach (DataRow drv in dv)
                {
                    AsyncTreeNode atn = new AsyncTreeNode();
                    atn.NodeID = drv["" + keyId + ""].ToString();
                    atn.Text = drv["" + keyname + ""].ToString();
                    atn.Qtip = drv["" + keyname + ""].ToString();

                    if (drv.Table.Columns.Contains("Icon") && !string.IsNullOrEmpty(drv["Icon"].ToString()))
                    {
                        atn.IconFile = "../resources/images/tree/" + drv["Icon"].ToString();
                    }

                    //判断下面是否还有数据，如果有就是用下级+ 没有了就不可点击下级
                    System.Data.DataRow[] rows = dtitem.Select(keyparent + " =" + atn.NodeID);
                    atn.Leaf = rows.Length == 0;

                    atn.Listeners.Click.Handler = "javascript:showForm(node)";
                    nodes.Add(atn);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return nodes.ToJson();
        }
        /// <summary>
        /// 如果在缓冲中的数据集中找不到就
        /// 显示第一级的数据并且是按照ID排序
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dr"></param>
        public void getDataRow(DataTable dt, ref DataRow[] dr, string sort)
        {

            DataRow[] rows = dt.Select("", AddFieldS["keyParent"].ToString());

            DataTable tempDataTable = dt.Clone();

            tempDataTable.Clear();

            foreach (DataRow row in rows)
                tempDataTable.ImportRow(row);

            dt = tempDataTable;

            if (dt.Rows.Count > 0)
                dr = dt.Select(AddFieldS["keyParent"].ToString() + "=" + dt.Rows[0]["" + AddFieldS["keyParent"].ToString() + ""], sort);
        }

        [AjaxMethod]
        public string GetSelNodeChildsId(int nodeId)
        {
            string childNodeIds = string.Empty;
            //string cachekey = ("TreeData_" + TableName + "_" + CurrentUser.LoginRole.Id).ToUpper();
            string keyId = AddFieldS["keyId"].ToString();
            string keyname = AddFieldS["keyName"].ToString();
            string keyparent = AddFieldS["keyParent"].ToString();

            //DataTable dt = (DataTable)_cache.RetrieveObject(cachekey);
            GetShowDataTable(false);
            try
            {
                DataRow[] childs = dtitem.Select(keyparent + "=" + nodeId);
                foreach (DataRow c in childs)
                {
                    childNodeIds += c[keyId].ToString() + ",";
                    childNodeIds += GetSelNodeChildsId(int.Parse(c[keyId].ToString()));
                }
            }
            catch
            {

            }

            return childNodeIds;
        }

        /// <summary>
        /// 刷新树的内容
        /// 重新获得内容
        /// （这儿考虑异步加载，只对树的某个节点进行刷新）
        /// </summary>
        /// <returns></returns>
        [AjaxMethod]
        public string RefreshTree()
        {
            GetShowDataTable(true);
            return InitTree("0");
        }

        /// <summary>
        /// 搜索事件+""
        /// </summary>
        /// <returns></returns>
        [AjaxMethod]
        public bool LodeSeach()
        {
            try
            {
                GetShowDataTable(true);
                string cachekey = ("TreeData_" + TableName + "_" + CurrentUser.LoginRole.Id).ToUpper();
                string txtsearch = txtFieldSearch.Text;
                if (!string.IsNullOrEmpty(txtsearch))
                {
                    string condition = " " + AddFieldS["keyName"].ToString() + " like '%" + txtsearch + "%'";
                    if (AddFieldS["keyCode"] != null && AddFieldS["keyAbbreviation"] != null)
                    {
                        condition += " or " + AddFieldS["keyCode"].ToString() + " like '%" + txtsearch + "%'";
                        condition += " or " + AddFieldS["keyAbbreviation"].ToString() + " like '%" + txtsearch + "%'";
                    }
                    dtitem = GetNewDataTable(condition);
                }
                //_cache.RemoveObject(cachekey);
                //_cache.AddObject(cachekey, dtitem);
                CacheManage.AddCacheObject(cachekey, dtitem, DataSourceType.ResourceData, resourceId);
            }
            catch { }
            return dtitem.Rows.Count > 0;
        }

        /// <summary>
        /// 通过自定义表达式进行搜索
        /// </summary>
        /// <param name="express">计算表达式</param>
        /// <returns>搜索是否成功</returns>
        [AjaxMethod]
        public bool LodeSeachByExpress(string express)
        {
            try
            {
                GetShowDataTable(true);
                string cachekey = ("TreeData_" + TableName + "_" + CurrentUser.LoginRole.Id).ToUpper();

                if (!string.IsNullOrEmpty(express))
                {
                    dtitem = GetNewDataTable(express);
                }

                CacheManage.AddCacheObject(cachekey, dtitem, DataSourceType.ResourceData, resourceId);
            }
            catch { }
            return dtitem.Rows.Count > 0;
        }


        /// <summary>
        /// 执行DataTable中的查询返回新的DataTable
        /// </summary>
        /// <param name="dtitem">源数据DataTable</param>
        /// <param name="condition">查询条件</param>
        /// <returns></returns>
        private DataTable GetNewDataTable(string condition)
        {
            //用来存放的到的
            DataTable dataTable = new DataTable();
            dataTable = dtitem.Clone();

            DataRow [] dr = dtitem.Select(condition);
            for (int i = 0; i < dr.Length; i++)
            {
                dataTable.ImportRow(dr[i]);
                //前序查询获得有关键字的数据遍历DataTable
                GetAllNodes(ref dataTable, dr[i]["" + AddFieldS["keyParent"].ToString() + ""].ToString());
                //后序查询
                GetNextNodes(ref dataTable, dr[i]["" + AddFieldS["keyId"].ToString() + ""].ToString());
            }

            string[] PrimaryKeyColumns = new string[dataTable.Columns.Count];
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                PrimaryKeyColumns[i] = dataTable.Columns[i].ToString();
            }
            //去掉重复值
            System.Data.DataView dv = dataTable.DefaultView;
            dataTable = dv.ToTable(true, PrimaryKeyColumns);

            return dataTable;//返回的查询结果
        }

        //得到有关键字的集合DataTable
        /// <summary>
        /// 后序遍历集合，
        /// 得到它上级的数据并且放到DataTable中
        /// </summary>
        /// <param name="rows">叶节点数据</param>
        /// <param name="newdata">集合DataTable用于存放满足条件的内容</param>
        /// <param name="pId">当前页节点的父级编号
        /// </param>
        /// <returns>满足条件的所有数据</returns>
        private DataTable GetAllNodes(ref DataTable dataTable, string pId)
        {
            //这是根据父级编号查询的方法，参数为选择项的编号查询它下面还有子类。
            try
            {
                DataRow[] dr = dtitem.Select(AddFieldS["keyId"].ToString() + "=" + pId);
                foreach (DataRow row in dr)
                {
                    dataTable.Rows.Add(row.ItemArray);
                    GetAllNodes(ref dataTable, row["" + AddFieldS["keyParent"].ToString() + ""].ToString());

                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return dataTable;
        }

        /// <summary>
        /// 后序查询树形
        ///递归查询 树的下级数据
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="nodeID"></param>
        private void GetNextNodes(ref DataTable dataTable, string nodeID)
        {
            try
            {
                DataRow[] dr = dtitem.Select(AddFieldS["keyParent"].ToString() + "=" + nodeID);
                if (dr.Length > 0)
                {
                    foreach (DataRow row in dr)
                    {
                        dataTable.Rows.Add(row.ItemArray);
                        GetNextNodes(ref dataTable, row["" + AddFieldS["keyId"].ToString() + ""].ToString());

                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }
    }
}